<template>
  <view class="workorder-container">
    <!-- 顶部搜索栏 -->
    <view class="header">
      <view class="header-content">
        <view class="search-container">
          <view class="search-box">
            <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
            <input type="text" placeholder="搜索采购单标题" v-model="searchKeyword" class="search-input"
              placeholder-class="search-placeholder" @input="onSearchInput" />
          </view>
          <view class="search-btn" @click="handleSearch">
            <text class="search-btn-text">搜索</text>
          </view>

          <!-- 新增按钮 -->
          <view class="add-btn" @click="showCreateForm" v-if="role === 1">
            <text class="add-btn-text">+</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类标签 -->
    <view class="category-tabs">
      <view v-for="(category, index) in statusList" :key="index" class="category-item"
        :class="[activeCategory === index ? 'active' : '']" @click="switchCategory(index)">
        <text class="category-text">{{ category.name }}</text>
      </view>
    </view>

    <!-- 采购单列表 -->
    <scroll-view class="workorder-list" scroll-y="true" @refresherrefresh="onRefresh"
      @scrolltolower="loadMore">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="filteredWorkorderList.length === 0" class="empty-state">
        <image src="/static/image/no_permission.png" class="empty-icon" mode="aspectFit"></image>
        <text class="empty-text">暂无采购单</text>
        <text class="empty-desc">快去创建采购单吧~</text>
      </view>

      <!-- 采购单列表 -->
      <view v-else class="workorder-list-container">
        <view v-for="(workorder, index) in filteredWorkorderList" :key="workorder.id" class="workorder-item">
          <!-- 采购单头部 -->
          <view class="workorder-header">
            <view class="workorder-date">
              <text class="date-text">{{ formatDate(workorder.menu_date) }}</text>
            </view>
            <view class="workorder-status" :class="[getStatusClass(workorder.status)]">
              <text class="status-text">{{ getStatusText(workorder.status) }}</text>
            </view>
          </view>

          <!-- 采购单信息 -->
          <view class="workorder-content" @click="viewWorkorderDetail(workorder)">
            <view class="workorder-info">
              <text class="workorder-title">{{ workorder.title }}</text>
              <text class="workorder-desc">{{ workorder.description || '暂无描述' }}</text>
            </view>

            <!-- 采购单信息 -->
            <view class="dish-info">
              <view class="dish-count">
                <text class="dish-label">供应商</text>
                <text class="dish-value">{{ workorder.supplier && workorder.supplier.name || '未指定' }}</text>
              </view>

              <view class="dish-price">
                <text class="price-label">采购员</text>
                <text class="price-value">{{ workorder.purchaser && workorder.purchaser.name || '未指定' }}</text>
              </view>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="workorder-actions">
<!--            <view v-if="role === 1 && workorder.status === 0" class="action-btn primary"-->
<!--              @click="editWorkorder(workorder)">-->
<!--              <text class="action-text">编辑</text>-->
<!--            </view>-->
            <view v-if="role === 1 && workorder.status === 0" class="action-btn primary"
              @click="selectDishes(workorder)">
              <text class="action-text">选择菜品</text>
            </view>
            <view v-if="role === 1 && workorder.status === 0" class="action-btn primary"
              @click="publishWorkorder(workorder)">
              <text class="action-text">提交</text>
            </view>
            <view v-if="role === 1 && workorder.status === 0" class="action-btn primary"
                  @click="deleteWorkorder(workorder)">
              <text class="action-text">删除</text>
            </view>
            <view v-if="role === 1 && workorder.status === 2" class="action-btn primary"
              @click="confirmReceipt(workorder)">
              <text class="action-text">确认收货</text>
            </view>
            <view v-if="role === 0 && workorder.status === 1" class="action-btn primary"
                  @click="confirmBuy(workorder)">
              <text class="action-text">采买</text>
            </view>

            <!-- 通用操作按钮 -->
            <view class="action-btn secondary" @click="viewWorkorderDetail(workorder)">
              <text class="action-text">购物车</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && !loading && userInfo.id" class="load-more" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>

      <!-- 没有更多 -->
      <view v-if="!hasMore && filteredWorkorderList.length > 0" class="no-more">
        <text class="no-more-text">没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import api from "../../config/api.js";

export default {
  data() {
    return {
      statusBarHeight: 0,
      navBarHeight: 44,
      searchKeyword: '',
      activeCategory: 0,
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10,
      workorderList: [],

      // 分类标签
      categories: [
        { name: '进行中', type: 'my' },
        { name: '已完成', type: 'all' }
      ],

      // 采购单状态
      statusList: [
        { key: 1, name: '待采购' },
        { key: 2, name: '待验收' },
        { key: 3, name: '已收货' },
        // { key: 4, name: '已完成' }
      ]
    }
  },

  computed: {
    // 过滤后的采购单列表
    filteredWorkorderList() {
      if (!this.searchKeyword) {
        return this.workorderList;
      }
      return this.workorderList.filter(item =>
        item.title && item.title.includes(this.searchKeyword)
      );
    }
  },

  onShow() {
    this.$store.dispatch('getUserInfo')

    if (this.role === 1) {
      this.statusList = [
        { key: 0, name: '草稿' },
        { key: 1, name: '待采购' },
        { key: 2, name: '待验收' },
        { key: 3, name: '已收货' },
        // { key: 4, name: '已完成' }
      ]
      this.activeCategory = 0
    }
    console.log(this.role, '----')
    this.loadWorkorderData();
  },

  methods: {
    // 切换分类
    switchCategory(index) {
      if (this.activeCategory === index) return;
      this.activeCategory = index;
      this.page = 1;
      this.hasMore = true;
      this.workorderList = [];
      this.loadWorkorderData();
    },

    // 搜索输入
    onSearchInput() {
      // 实时搜索逻辑
    },

    // 执行搜索
    handleSearch() {
      this.page = 1;
      this.hasMore = true;
      this.workorderList = [];
      this.loadWorkorderData();
    },

    // 加载采购单数据
    loadWorkorderData() {

      if (!this.userInfo.id) return;
      if (this.loading) return;

      this.loading = true;
      const params = {
        pageNo: this.page,
        pageSize: this.pageSize,
        title: this.searchKeyword,
        status: this.statusList[this.activeCategory].key
      };
      console.log(this.role === 1)
      if (this.role === 1) {
        params.purchaser_id = this.userInfo.id || ''
      } else {
        params.supplier_id = this.userInfo.id || ''
      }

      // 调用API获取采购单列表
      api.getDailyMenuList(params).then(response => {
        const data = response.list || [];
        if (this.page === 1) {
          this.workorderList = data;
        } else {
          this.workorderList = [...this.workorderList, ...data];
        }

        this.hasMore = data.length === this.pageSize;
        this.loading = false;
      }).catch(error => {
        console.error('加载采购单列表失败:', error);
        this.loading = false;
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        0: 'status-pending',
        1: 'status-processing',
        2: 'status-completed',
        3: 'status-accepted',
        4: 'status-published'
      };
      return statusMap[status] || 'status-pending';
    },

    // 获取状态文本
    getStatusText(status) {
      const statusItem = this.statusList.find(item => item.key === status);
      return statusItem ? statusItem.name : '未知状态';
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 查看采购单详情
    viewWorkorderDetail(workorder) {
      uni.navigateTo({
        url: `/pages/workorder/detail?id=${workorder.id}`
      });
    },

    // 编辑采购单
    editWorkorder(workorder) {
      uni.navigateTo({
        url: `/pages/workorder/create?id=${workorder.id}`
      });
    },

    // 选择菜品
    selectDishes(workorder) {
      uni.navigateTo({
        url: `/pages/workorder/dishes?id=${workorder.id}`
      });
    },

    // 发布采购单
    publishWorkorder(workorder) {
      uni.showModal({
        title: '确认操作',
        content: '确定要发布该采购单吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '发布中...',
            })
            api.updateDailyMenu(workorder.id, {
              status: 1
            }).then(() => {
              uni.hideLoading();
              uni.showToast({
                title: '发布成功',
                icon: 'success'
              });
              this.loadWorkorderData();
            })
          }
        }
      });
    },
// deleteWorkorder
    deleteWorkorder(workorder) {
      uni.showModal({
        title: '确认操作',
        content: '确定要删除该采购单吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '发布中...',
            })
            api.deleteDailyMenu(workorder.id).then(() => {
              uni.hideLoading();
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              this.loadWorkorderData();
            })
          }
        }
      });
    },

    // 确认收货
    confirmReceipt(workorder) {
      uni.navigateTo({
        url: `/pages/workorder/receipt?id=${workorder.id}`
      });
    },
    confirmBuy(workorder) {
      uni.navigateTo({
        url: `/pages/workorder/buy?id=${workorder.id}`
      });
    },
    // 查看收货明细
    viewReceiptDetails(workorder) {
      uni.navigateTo({
        url: `/pages/workorder/details?id=${workorder.id}`
      });
    },

    // 显示创建表单
    showCreateForm() {
      uni.navigateTo({
        url: '/pages/workorder/create'
      });
    },

    // 下拉刷新
    onRefresh() {
      this.page = 1;
      this.hasMore = true;
      this.loadWorkorderData();
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return;
      this.page++;
      this.loadWorkorderData();
    }
  }
}
</script>

<style lang="scss">
.workorder-container {
  height: 100%;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
}

// 顶部搜索栏
.header {
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .header-content {
    .search-container {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .search-box {
        flex: 1;
        display: flex;
        align-items: center;
        background-color: #f8f8f8;
        border-radius: 24rpx;
        padding: 16rpx 24rpx;
        gap: 12rpx;

        .search-icon {
          width: 32rpx;
          height: 32rpx;
        }

        .search-input {
          flex: 1;
          font-size: 28rpx;
          color: #333;
        }

        .search-placeholder {
          color: #999;
        }
      }

      .search-btn {
        padding: 16rpx 24rpx;
        background-color: #FFC300;
        border-radius: 24rpx;

        .search-btn-text {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

// 分类标签
.category-tabs {
  background-color: #fff;
  display: flex;
  padding: 0 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;

  .category-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 24rpx 0;
    position: relative;

    &.active {
      .category-text {
        color: #FFC300;
        font-weight: 600;
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background-color: #FFC300;
        border-radius: 2rpx;
      }
    }

    .category-text {
      font-size: 32rpx;
      color: #666;
      transition: all 0.3s;
    }
  }
}

// 采购单列表
.workorder-list {
  height: calc(100vh - 200rpx);
}

// 加载状态
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;

  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  padding: 0 32rpx;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #ccc;
  }
}

.workorder-list-container {
  padding: 0 32rpx;
}

.workorder-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
}

// 采购单头部
.workorder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .workorder-date {
    .date-text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }

  .workorder-status {
    padding: 8rpx 16rpx;
    border-radius: 8rpx;
    font-size: 24rpx;

    &.status-pending {
      background-color: #fff8e1;
      color: #ff9800;
    }

    &.status-processing {
      background-color: #e3f2fd;
      color: #2196f3;
    }

    &.status-completed {
      background-color: #e8f5e8;
      color: #4caf50;
    }

    &.status-accepted {
      background-color: #e8f5e8;
      color: #4caf50;
    }

    &.status-published {
      background-color: #f3e5f5;
      color: #9c27b0;
    }

    .status-text {
      font-weight: 500;
    }
  }
}

// 采购单内容
.workorder-content {
  padding: 24rpx 32rpx;

  .workorder-info {
    margin-bottom: 24rpx;

    .workorder-title {
      font-size: 32rpx;
      color: #333;
      font-weight: 600;
      line-height: 1.4;
      margin-bottom: 12rpx;
    }

    .workorder-desc {
      font-size: 26rpx;
      color: #666;
      line-height: 1.5;
    }
  }

  .dish-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-top: 1rpx solid #f0f0f0;

    .dish-count {
      display: flex;
      align-items: center;
      gap: 12rpx;

      .dish-label {
        font-size: 26rpx;
        color: #666;
      }

      .dish-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }

    .dish-price {
      display: flex;
      align-items: center;
      gap: 12rpx;

      .price-label {
        font-size: 26rpx;
        color: #666;
      }

      .price-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
}

// 操作按钮
.workorder-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 16rpx;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;

  .action-btn {
    padding: 12rpx 24rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
    font-weight: 500;

    &.primary {
      background-color: #FFC300;
      color: #333;
    }

    &.secondary {
      background-color: #f5f5f5;
      color: #666;
    }

    .action-text {
      font-size: 26rpx;
    }
  }
}

// 加载更多
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  margin: 40rpx 0;

  .load-more-text {
    font-size: 28rpx;
    color: #666;
  }
}

.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80rpx;
  margin: 40rpx 0;

  .no-more-text {
    font-size: 24rpx;
    color: #ccc;
  }
}

// 新增按钮
.add-btn {
  width: 100rpx;
  height: 70rpx;
  background-color: #FFC300;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
  border-radius: 12rpx;

  .add-btn-text {
    font-size: 48rpx;
    color: #333;
    font-weight: 600;
  }
}
</style>
